﻿using log4net;
using Microsoft.VisualBasic;
using Microsoft.VisualBasic.Logging;
using Modules.ActionRun;
using Modules.MSentEvent;
using Modules.TaskMan.ViewModels;
using Modules.Units;
using Newtonsoft.Json;
using Prism.Events;
using RabbitMQ;
using RabbitMQ.Client;
using Sorting.App.Controls;
using Sorting.App.Models;
using Sorting.App.Models.Enum;
using Sorting.App.Services;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using static Sorting.App.Controls.MyMessageBox;

namespace Modules.TaskMan.Views
{
    /// <summary>
    /// ViewTaskMainV2.xaml 的交互逻辑
    /// </summary>
    public partial class ViewTaskMainV2 : UserControl
    {
        private ViewTaskMainV2ViewModel _viewModel;
        private ShelfService shelfService = new ShelfService();
        IEventAggregator _ea;
        public ViewTaskMainV2(ViewTaskMainV2ViewModel viewModel, IEventAggregator ea)
        {
            InitializeComponent();
            _viewModel = viewModel;
            _ea = ea;
            ReloadShelfGrid();
            //监听RabbitMq队列处理
            //全局异常处理
            MQHelperFactory.SortingView().Receive("SortingView.Error", false, AllError);
            MQHelperFactory.SortingView().Receive("SortingView.SendFinish", false, SendFinish);
            MQHelperFactory.SortingView().Receive("SortingView.PutCount", false, PutCount);
            MQHelperFactory.SortingView().Receive("SortingView.CountFinish", false, CountFinish);
            MQHelperFactory.SortingView().Receive("SortingView.ScanCount", false, ScanCount);
            MQHelperFactory.SortingView().Receive("SortingView.ErrorCount", false, ErrorCount);
            MQHelperFactory.SortingView().Receive("SortingView.WorkerService", false, WorkerServiceLife);
            MQHelperFactory.SortingView().Receive("SortingView.OrgState", false, OrgState);
            MQHelperFactory.SortingView().Receive("SortingView.RunStatus", false, RunStatus);

            _ea.GetEvent<ViewModelSentEvent>().Subscribe(LoginSucess,
             arg => arg.Code.Equals(EnumMessageType.ME101));
            Task.Run(async () =>
            {
                while (true)
                {
                    await Task.Delay(1000);

                    if (System.Diagnostics.Process.GetProcessesByName("SortingWorkerService").ToList().Count > 0)
                    {
                        Console.WriteLine("SortingWorkerService正在运行");
                        AppsettingUnits.IsWorkerServiceLife = true;
                    }
                    else
                    {
                        AppsettingUnits.IsWorkerServiceLife = false;
                    }


                }
            });
        }

        #region RabbitMq消息监听动作

        /// <summary>
        /// 执行服务存活
        /// </summary>
        /// <param name="obj"></param>
        /// <exception cref="NotImplementedException"></exception>

        private bool WorkerServiceLife(string obj, ulong DeliveryTag, IModel channel)
        {
            var data = JsonConvert.DeserializeObject<RabbitSend<bool>>(obj);

            AppsettingUnits.IsWorkerServiceLife = (bool)data.TaskData;
            channel.BasicAck(DeliveryTag, false);
            return true;

        }

        public bool RunStatus(string obj, ulong DeliveryTag, IModel channel)
        {
            try
            {
                if (_viewModel.BtnStartTxt.ToString() == "停止")
                {
                    this.Dispatcher.Invoke(() =>
                    {

                        _viewModel.PerformbtnStartTask();

                    });

                }
                else
                {
                    Debug.WriteLine("第一次加载");
                }
                channel.BasicAck(DeliveryTag, false);
                return true;
            }
            catch (Exception)
            {
                channel.BasicAck(DeliveryTag, false);
                return false;
                throw;
            }



        }

        /// <summary>
        /// 全局异常
        /// </summary>
        /// <param name="obj"></param>
        private bool AllError(string obj, ulong DeliveryTag, IModel channel)
        {
            try
            {

                //_viewModel.btnStartTxt = "启动";
                //_viewModel.IsTaskStart = false;

                //   MessageBox.Show("设备错误");
                channel.BasicAck(DeliveryTag, false);
                return true;
            }
            catch (Exception)
            {
                channel.BasicAck(DeliveryTag, false);
                return false;
                throw;
            }

        }

        /// <summary>
        /// 下发完成
        /// </summary>
        /// <param name="obj"></param>
        /// <exception cref="NotImplementedException"></exception>
        private bool SendFinish(string obj, ulong DeliveryTag, IModel channel)
        {
            try
            {

                var data = JsonConvert.DeserializeObject<RabbitSend<ShelfEntity>>(obj);

                var shelfdata = data.TaskData;
                this.Dispatcher.Invoke(() =>
                {

                    this.labHasTasksCount.Content = "已下发：" + data.TaskMessage;

                });
                //更新界面对应储位指示灯状态
                var resshelf = _viewModel.ShelfEntities.Where(t => t.ShelfUuid == shelfdata.Uuid).FirstOrDefault();//当前储位信息
                if (shelfdata.Allstock == shelfdata.Max)
                    resshelf.ShelfState = EnumStockBoxState.Full;
                resshelf.TaskState = EnumTaskState.Sucess;
                _viewModel.ShelfEntitiesA = _viewModel.ShelfEntities.Where(t => t.LeftOrRight.Equals("L")).ToList();
                _viewModel.ShelfEntitiesB = _viewModel.ShelfEntities.Where(t => t.LeftOrRight.Equals("R")).ToList();

                this.Dispatcher.Invoke(() =>
                {
                    this.DataContext = _viewModel;
                    this.InitA(this.StockGridA);

                    this.InitB(this.StockGridB);
                });
                channel.BasicAck(DeliveryTag, false);
                return true;
            }
            catch (Exception)
            {
                channel.BasicAck(DeliveryTag, false);
                return false;
                throw;
            }

        }

        private ulong PutCountoldTag = 0;
        /// <summary>
        /// 放入计数
        /// </summary>
        /// <param name="obj"></param>
        /// <exception cref="NotImplementedException"></exception>
        private bool PutCount(string obj, ulong DeliveryTag, IModel channel)
        {
            try
            {
                var data = JsonConvert.DeserializeObject<RabbitSend<int>>(obj);
                if (data.TaskType == "任务执行中")
                {
                    //更新界面对应储位指示灯状态
                    var resshelf = _viewModel.ShelfEntities.Where(t => t.ShelfUuid == data.TaskData.ToString()).FirstOrDefault();//当前已入队个数
                    if (resshelf != null)
                    {
                        resshelf.TaskState = EnumTaskState.Running;
                        _viewModel.ShelfEntitiesA = _viewModel.ShelfEntities.Where(t => t.LeftOrRight.Equals("L")).ToList();
                        _viewModel.ShelfEntitiesB = _viewModel.ShelfEntities.Where(t => t.LeftOrRight.Equals("R")).ToList();

                        //小屏信息
                        //解析地址
                        string shelfName = resshelf.ShelfName;
                        string iShelfName = "";
                        string[] parts = shelfName.Split('-'); // 按照 "-" 分割字符串
                        if (parts.Length != 3)
                        {
                            //log.Error("位置错误");
                        }
                        if (parts[0] == "L")
                        {
                            iShelfName += "1";
                        }
                        else if (parts[0] == "R")
                        {
                            iShelfName += "2";
                        }
                        iShelfName += parts[1];
                        iShelfName += parts[2];

                        //同步小屏等待中状态
                        SmallScreanHelper.WriteWaitState(iShelfName);

                        this.Dispatcher.Invoke(() =>
                        {
                            this.DataContext = _viewModel;
                            this.InitA(this.StockGridA);

                            this.InitB(this.StockGridB);
                        });
                    }

                }
                else
                {
                    this.Dispatcher.Invoke(() =>
                    {
                        this.labPutCount.Content = "已进入：" + data.TaskData;
                    });
                }
                channel.BasicAck(DeliveryTag, false);
                return true;
            }
            catch (Exception ex)
            {
                channel.BasicAck(DeliveryTag, false);
                return false;
                throw;
            }

        }
        /// <summary>
        /// 已扫描
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="DeliveryTag"></param>
        /// <param name="channel"></param>
        /// <returns></returns>

        private bool ScanCount(string obj, ulong DeliveryTag, IModel channel)
        {
            try
            {
                var data = JsonConvert.DeserializeObject<RabbitSend<int>>(obj);
                this.Dispatcher.Invoke(() =>
                {
                    this.labScanCount.Content = "已扫描：" + data.TaskData;  //扫描+1
                });
                channel.BasicAck(DeliveryTag, false);
                return true;
            }
            catch (Exception ex)
            {
                channel.BasicAck(DeliveryTag, false);
                return false;
                throw;
            }

        }


        /// <summary>
        /// 计数已结束
        /// </summary>
        /// <param name="obj"></param>
        /// <exception cref="NotImplementedException"></exception>
        private bool CountFinish(string obj, ulong DeliveryTag, IModel channel)
        {
            try
            {

                //更新库存  刷新界面
                var data = JsonConvert.DeserializeObject<RabbitSend<ShelfEntity>>(obj);
                var shelfdata = data.TaskData;

                //小屏信息
                //解析地址
                string shelfName = shelfdata.Name;
                string iShelfName = "";
                string[] parts = shelfName.Split('-'); // 按照 "-" 分割字符串
                if (parts.Length != 3)
                {
                    //log.Error("位置错误");
                }
                if (parts[0] == "L")
                {
                    iShelfName += "1";
                }
                else if (parts[0] == "R")
                {
                    iShelfName += "2";
                }
                iShelfName += parts[1];
                iShelfName += parts[2];

                SmallScreanHelper.WriteCurNum(iShelfName, shelfdata.Allstock);//同步小屏当前数量

                Task.Run(async () =>
                {
                    await _viewModel.RealoadShelf();

                    this.Dispatcher.Invoke(() =>
                    {

                        InitA(this.StockGridA);

                        InitB(this.StockGridB);
                    });
                });
                channel.BasicAck(DeliveryTag, false);
                return true;
            }
            catch (Exception)
            {
                channel.BasicAck(DeliveryTag, false);
                return false;
                throw;
            }

        }

        /// <summary>
        /// 异常数量
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="DeliveryTag"></param>
        /// <param name="channel"></param>
        /// <returns></returns>
        public bool ErrorCount(string obj, ulong DeliveryTag, IModel channel)
        {
            try
            {
                var data = JsonConvert.DeserializeObject<RabbitSend<int>>(obj);
                this.Dispatcher.Invoke(() =>
                {
                    this.lblErrorCount.Content = "异常：" + data.TaskData;
                });
                channel.BasicAck(DeliveryTag, false);
                return true;
            }
            catch (Exception ex)
            {
                channel.BasicAck(DeliveryTag, false);
                return false;
                throw;
            }
        }

        private bool OrgState(string obj, ulong DeliveryTag, IModel channel)
        {
            var data = JsonConvert.DeserializeObject<RabbitSend<bool>>(obj);


            channel.BasicAck(DeliveryTag, false);


            return true;

        }
        #endregion

        /// <summary>
        /// 登录成功
        /// </summary>
        /// <param name="obj"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void LoginSucess(MessageModel obj)
        {
            //_viewModel.AllIsEnable = true;
            if (AppsettingUnits.Appseeting.Local)
            {
                _viewModel.UserName = "管理员";
                Admin.Visibility = Visibility.Visible;
            }
            else
            {
                _viewModel.UserName = AppsettingUnits.CaCheUserInfo.Name;
                Admin.Visibility = Visibility.Hidden;
            }
            this.DataContext = _viewModel;
        }

        #region 界面处理
        private int Row = 3;
        private int Col = 7;
        public List<ShelfJoinWardModel> shelfEntitysA = new List<ShelfJoinWardModel>();

        public List<ShelfJoinWardModel> shelfEntitysB = new List<ShelfJoinWardModel>();

        /// <summary>
        /// 重新绘制界面
        /// </summary>
        private void ReloadShelfGrid()
        {
            this.Dispatcher.Invoke(async () =>
            {
                await _viewModel.RealoadShelf();
                InitA(this.StockGridA);

                InitB(this.StockGridB);

            });
        }

        /// <summary>
        /// 生成行
        /// </summary>
        /// <param name="rowCount"></param>
        /// <param name="g"></param>
        private void InitRows(int rowCount, Grid g)
        {
            while (rowCount-- > 0)
            {
                RowDefinition rd = new RowDefinition();
                rd.Height = new GridLength();
                g.RowDefinitions.Add(rd);
            }
        }
        /// <summary>
        /// 生成列
        /// </summary>
        /// <param name="colCount"></param>
        /// <param name="g"></param>
        private void InitColumns(int colCount, Grid g)
        {
            while (colCount-- > 0)
            {
                ColumnDefinition rd = new ColumnDefinition();
                rd.Width = new GridLength();
                g.ColumnDefinitions.Add(rd);
            }
        }
        /// <summary>
        /// 初始行列绘制加入显示的内容  A模块
        /// </summary>
        /// <param name="g"></param>
        private void InitA(Grid g)
        {
            g.Children.Clear();
            shelfEntitysA = _viewModel.ShelfEntitiesA;


            //需要绘制的总行数
            //Row = Math.Ceiling(Convert.ToDecimal(shelfEntitysA.Count / Col));

            //整行
            var ZRow = Math.Floor(Convert.ToDecimal(shelfEntitysA.Count / Col));
            //剩余需要绘制的列数量
            var YCol = Convert.ToDecimal(shelfEntitysA.Count % Col);

            var NowCol = shelfEntitysA.Count > Col ? Col : shelfEntitysA.Count;
            InitRows((int)Row, g);
            InitColumns((int)Col, g);


            //实体列表对应的当前下标
            var entityI = 0;

            //先绘制整行
            for (int r = (int)ZRow; r > 0; r--)
            {
                for (int c = 0; c < NowCol; c++)
                {

                    var item = shelfEntitysA[entityI];
                    Grid grid = InitStockBox(item);

                    g.Children.Add(grid);
                    Grid.SetColumn(grid, c);
                    if (YCol <= 0)
                    {
                        Grid.SetRow(grid, r - 1);
                    }
                    else
                    {
                        Grid.SetRow(grid, r);
                    }

                    entityI++;
                }
                //entityI += (int)Col;
            }
            //绘制剩余部分
            if (YCol > 0)
            {
                for (int c = 0; c < YCol; c++)
                {

                    var item = shelfEntitysA[entityI];
                    Grid grid = InitStockBox(item);

                    g.Children.Add(grid);
                    Grid.SetColumn(grid, c);
                    // Grid.SetRow(grid, (int)ZRow + 1);
                    Grid.SetRow(grid, 0);
                    entityI++;
                }
            }
        }
        /// <summary>
        /// 初始行列绘制加入显示的内容  B模块
        /// </summary>
        /// <param name="g"></param>
        private void InitB(Grid g)
        {
            g.Children.Clear();
            shelfEntitysB = _viewModel.ShelfEntitiesB;

            //需要绘制的总行数
            //Row = Math.Ceiling(Convert.ToDecimal(shelfEntitysB.Count / Col));

            //整行
            var ZRow = Math.Floor(Convert.ToDecimal(shelfEntitysB.Count / Col));
            //剩余需要绘制的列数量
            var YCol = Convert.ToDecimal(shelfEntitysB.Count % Col);

            var NowCol = shelfEntitysB.Count > Col ? Col : shelfEntitysB.Count;
            InitRows((int)Row, g);
            InitColumns((int)Col, g);


            //实体列表对应的当前下标
            var entityI = 0;

            //先绘制整行
            for (int r = (int)ZRow; r > 0; r--)
            {
                for (int c = 0; c < NowCol; c++)
                {

                    var item = shelfEntitysB[entityI];
                    Grid grid = InitStockBox(item);

                    g.Children.Add(grid);
                    Grid.SetColumn(grid, c);
                    if (YCol <= 0)
                    {
                        Grid.SetRow(grid, r - 1);
                    }
                    else
                    {
                        Grid.SetRow(grid, r);
                    }



                    entityI++;
                }
                //entityI += (int)Col;
            }
            //绘制剩余部分
            if (YCol > 0)
            {
                for (int c = 0; c < YCol; c++)
                {

                    var item = shelfEntitysB[entityI];
                    Grid grid = InitStockBox(item);

                    g.Children.Add(grid);
                    Grid.SetColumn(grid, c);
                    // Grid.SetRow(grid, (int)ZRow + 1);
                    Grid.SetRow(grid, 0);
                    entityI++;
                }
            }
        }



        /// <summary>
        /// 生成单个储位盒子样式
        /// </summary>
        private Grid InitStockBox(ShelfJoinWardModel shelfEntity)
        {
            var VenRateValue = Math.Round(Convert.ToDouble(shelfEntity.ShelfAllStock) / Convert.ToDouble(shelfEntity.ShelfMax), 2) * 100;
            //内部Grid样式
            Grid grid = new Grid();
            grid.Margin = new Thickness(15, 20, 15, 10);
            grid.Height = 95;
            grid.Width = 172;
            grid.Tag = shelfEntity.ShelfUuid;
            var view = new StoreViewItem();
            view.WardNameValue = shelfEntity.WardName;
            view.LocNameValue = "位置：" + shelfEntity.ShelfName;//L-1-1
            view.ScanNumValue = shelfEntity.ShelfAllStock;
            view.HasInVenNumValue = shelfEntity.ShelfAllStock;//当前数量
            view.StoreStateValue = shelfEntity.ShelfState;//储位状态
            view.TaskRunStateValue = shelfEntity.TaskState;//运行状态

            //小屏信息
            //解析地址
            string shelfName = shelfEntity.ShelfName;
            string iShelfName = "";
            string[] parts = shelfName.Split('-'); // 按照 "-" 分割字符串
            if (parts.Length != 3)
            {
                //log.Error("位置错误");
            }
            if (parts[0] == "L")
            {
                iShelfName += "1";
            }
            else if (parts[0] == "R")
            {
                iShelfName += "2";
            }
            iShelfName += parts[1];
            iShelfName += parts[2];
            //SmallScreanHelper.WriteWreaName(iShelfName, shelfEntity.WardName);//同步小屏名称
            //SmallScreanHelper.WriteMaxNum(iShelfName, shelfEntity.ShelfMax);//同步小屏最大数量

            if (shelfEntity.ShelfState == EnumStockBoxState.Full)
            {
                view.TaskRunStateValue = EnumTaskState.Fail;
                SmallScreanHelper.WriteFullState(iShelfName);//桶满状态
            }

            view.VenRateValue = (VenRateValue.ToString() == "∞" || VenRateValue.ToString() == "NaN") ? 100 : VenRateValue;
            grid.Children.Add(view);
            grid.MouseLeftButtonUp += async (s, e) =>
            {
                var res = MessageBoxHelper.ShowDialog<MessageBoxSimple>(null, "是否清空储位", "是", "否");
                if (res.Button == MessageBoxResultButton.Yes)
                {
                    MQHelperFactory.SortingView().SendMsg<RabbitSend<bool>>("Sorting.SendStartKeyout", new RabbitSend<dynamic>
                    {
                        TaskData = true
                    });
                    // 查询是哪一个储位
                    var shelf = await shelfService.GetShelfEntityByUuid(grid.Tag.ToString());

                    if (shelf != null)
                    {
                        shelf.Allstock = 0;
                        shelf.State = EnumStockBoxState.NoHas;
                        await shelfService.UpdateShelfStore(shelf);
                        var resshelf = _viewModel.ShelfEntities.Where(t => t.ShelfUuid == grid.Tag.ToString()).FirstOrDefault();
                        resshelf.ShelfState = EnumStockBoxState.NoHas;
                        resshelf.TaskState = default;
                        resshelf.ScanNum = 0;
                        resshelf.ShelfAllStock = 0;
                        //_viewModel.BtnStartTxt = btnStartTask.Content;
                        //_viewModel.ShelfEntitiesA = _viewModel.ShelfEntities.Where(t => t.LeftOrRight.Equals("L")).ToList();
                        //_viewModel.ShelfEntitiesB = _viewModel.ShelfEntities.Where(t => t.LeftOrRight.Equals("R")).ToList();

                        //解析地址   小屏
                        string shelfName = shelf.Name;
                        string iShelfName = "";
                        string[] parts = shelfName.Split('-'); // 按照 "-" 分割字符串
                        if (parts.Length != 3)
                        {
                            //log.Error("位置错误");
                        }
                        if (parts[0] == "L")
                        {
                            iShelfName += "1";
                        }
                        else if (parts[0] == "R")
                        {
                            iShelfName += "2";
                        }
                        iShelfName += parts[1];
                        iShelfName += parts[2];
                        SmallScreanHelper.WriteClearState(iShelfName);//同步小屏 清空状态

                        this.Dispatcher.Invoke(() =>
                        {
                            this.DataContext = _viewModel;
                            this.InitA(this.StockGridA);
                            this.InitB(this.StockGridB);
                        });
                    }

                }

            };
            return grid;
        }
        public SolidColorBrush SetBordbacColor(EnumStockBoxState type)
        {

            var SolidColorBrush = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#326cf3"));
            switch (type)
            {
                case EnumStockBoxState.NoUse:
                    SolidColorBrush = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#326cf3"));
                    break;
                case EnumStockBoxState.NoHas:
                    SolidColorBrush = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#326cf3"));
                    break;
                case EnumStockBoxState.NoFull:
                    SolidColorBrush = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#326cf3"));
                    break;
                case EnumStockBoxState.Full:
                    SolidColorBrush = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#f39c12"));
                    break;
                case EnumStockBoxState.Error:
                    SolidColorBrush = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#e74c3c"));
                    break;
                case EnumStockBoxState.Busy:
                    SolidColorBrush = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#2ecc71"));
                    break;
                case EnumStockBoxState.Flash:
                    SolidColorBrush = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#ffffff"));
                    break;
                case EnumStockBoxState.Running:
                    SolidColorBrush = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#f9c915"));
                    break;
                default:
                    break;
            }

            return SolidColorBrush;
        }
    }
    #endregion


}

